// 用户注册表单验证 Schema
// 支持用户注册和认证功能

/**
 * 用户表单字段配置
 */
export const USER_FORM_FIELDS = {
    username: {
        label: '用户名',
        placeholder: '请输入用户名',
        required: true,
        minLength: 3,
        maxLength: 50,
        pattern: /^[a-zA-Z0-9_]+$/,
        patternMessage: '用户名只能包含字母、数字和下划线'
    },
    email: {
        label: '邮箱',
        placeholder: '请输入邮箱地址',
        required: true,
        type: 'email',
        maxLength: 255
    },
    password: {
        label: '密码',
        placeholder: '请输入密码',
        required: true,
        minLength: 8,
        maxLength: 50,
        pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/,
        patternMessage: '密码必须包含大小写字母和数字'
    },
    confirmPassword: {
        label: '确认密码',
        placeholder: '请再次输入密码',
        required: true
    },
    fullName: {
        label: '姓名',
        placeholder: '请输入真实姓名',
        required: true,
        maxLength: 100
    },
    organization: {
        label: '机构',
        placeholder: '请输入所属机构或公司（可选）',
        required: false,
        maxLength: 200
    },
    department: {
        label: '部门',
        placeholder: '请输入部门（可选）',
        required: false,
        maxLength: 100
    },
    phone: {
        label: '电话',
        placeholder: '请输入联系电话（可选）',
        required: false,
        maxLength: 20,
        pattern: /^1[3-9]\d{9}$/,
        patternMessage: '请输入有效的手机号码'
    },
    applicationReason: {
        label: '申请理由',
        placeholder: '请简要说明您申请使用本平台的原因和用途...',
        required: true,
        type: 'textarea',
        maxLength: 1000,
        rows: 4
    }
}

/**
 * 验证用户名
 * @param {string} username - 用户名
 * @returns {string|null} 错误信息或 null
 */
export function validateUsername(username) {
    const config = USER_FORM_FIELDS.username

    if (!username || username.trim().length === 0) {
        return `${config.label}不能为空`
    }

    if (username.length < config.minLength) {
        return `${config.label}不能少于 ${config.minLength} 个字符`
    }

    if (username.length > config.maxLength) {
        return `${config.label}不能超过 ${config.maxLength} 个字符`
    }

    if (!config.pattern.test(username)) {
        return config.patternMessage
    }

    return null
}

/**
 * 验证邮箱
 * @param {string} email - 邮箱地址
 * @returns {string|null} 错误信息或 null
 */
export function validateEmail(email) {
    const config = USER_FORM_FIELDS.email

    if (!email || email.trim().length === 0) {
        return `${config.label}不能为空`
    }

    if (email.length > config.maxLength) {
        return `${config.label}不能超过 ${config.maxLength} 个字符`
    }

    const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    if (!emailPattern.test(email)) {
        return '请输入有效的邮箱地址'
    }

    return null
}

/**
 * 验证密码
 * @param {string} password - 密码
 * @returns {string|null} 错误信息或 null
 */
export function validatePassword(password) {
    const config = USER_FORM_FIELDS.password

    if (!password || password.length === 0) {
        return `${config.label}不能为空`
    }

    if (password.length < config.minLength) {
        return `${config.label}不能少于 ${config.minLength} 个字符`
    }

    if (password.length > config.maxLength) {
        return `${config.label}不能超过 ${config.maxLength} 个字符`
    }

    if (!config.pattern.test(password)) {
        return config.patternMessage
    }

    return null
}

/**
 * 验证确认密码
 * @param {string} confirmPassword - 确认密码
 * @param {string} password - 原密码
 * @returns {string|null} 错误信息或 null
 */
export function validateConfirmPassword(confirmPassword, password) {
    if (!confirmPassword || confirmPassword.length === 0) {
        return '请确认密码'
    }

    if (confirmPassword !== password) {
        return '两次输入的密码不一致'
    }

    return null
}

/**
 * 验证姓名
 * @param {string} fullName - 姓名
 * @returns {string|null} 错误信息或 null
 */
export function validateFullName(fullName) {
    const config = USER_FORM_FIELDS.fullName

    if (!fullName || fullName.trim().length === 0) {
        return `${config.label}不能为空`
    }

    if (fullName.length > config.maxLength) {
        return `${config.label}不能超过 ${config.maxLength} 个字符`
    }

    return null
}

/**
 * 验证申请理由
 * @param {string} applicationReason - 申请理由
 * @returns {string|null} 错误信息或 null
 */
export function validateApplicationReason(applicationReason) {
    const config = USER_FORM_FIELDS.applicationReason

    if (!applicationReason || applicationReason.trim().length === 0) {
        return `${config.label}不能为空`
    }

    if (applicationReason.length > config.maxLength) {
        return `${config.label}不能超过 ${config.maxLength} 个字符`
    }

    return null
}

/**
 * 验证手机号码
 * @param {string} phone - 手机号码
 * @returns {string|null} 错误信息或 null
 */
export function validatePhone(phone) {
    const config = USER_FORM_FIELDS.phone

    if (!phone || phone.trim().length === 0) {
        return null // 手机号码是可选的
    }

    if (!config.pattern.test(phone)) {
        return config.patternMessage
    }

    return null
}

/**
 * 完整的用户注册表单验证
 * @param {Object} formData - 表单数据
 * @returns {Object} 验证结果 { isValid, errors }
 */
export function validateUserForm(formData) {
    const errors = {}

    // 验证用户名
    const usernameError = validateUsername(formData.username)
    if (usernameError) errors.username = usernameError

    // 验证邮箱
    const emailError = validateEmail(formData.email)
    if (emailError) errors.email = emailError

    // 验证密码
    const passwordError = validatePassword(formData.password)
    if (passwordError) errors.password = passwordError

    // 验证确认密码
    const confirmPasswordError = validateConfirmPassword(formData.confirmPassword, formData.password)
    if (confirmPasswordError) errors.confirmPassword = confirmPasswordError

    // 验证姓名
    const fullNameError = validateFullName(formData.fullName)
    if (fullNameError) errors.fullName = fullNameError

    // 验证申请理由
    const applicationReasonError = validateApplicationReason(formData.applicationReason)
    if (applicationReasonError) errors.applicationReason = applicationReasonError

    // 验证手机号码（可选）
    const phoneError = validatePhone(formData.phone)
    if (phoneError) errors.phone = phoneError

    return {
        isValid: Object.keys(errors).length === 0,
        errors
    }
}

/**
 * 获取字段的 Ant Design 表单规则
 * @param {string} fieldName - 字段名称
 * @param {Object} formData - 当前表单数据（用于条件验证）
 * @returns {Array} Ant Design 表单规则数组
 */
export function getUserFieldRules(fieldName, formData = {}) {
    const rules = []

    switch (fieldName) {
        case 'username':
            rules.push(
                { required: true, message: '请输入用户名' },
                { min: 3, message: '用户名不能少于 3 个字符' },
                { max: 50, message: '用户名不能超过 50 个字符' },
                { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线' }
            )
            break

        case 'email':
            rules.push(
                { required: true, message: '请输入邮箱地址' },
                { type: 'email', message: '请输入有效的邮箱地址' },
                { max: 255, message: '邮箱地址不能超过 255 个字符' }
            )
            break

        case 'password':
            rules.push(
                { required: true, message: '请输入密码' },
                { min: 8, message: '密码不能少于 8 个字符' },
                { max: 50, message: '密码不能超过 50 个字符' },
                { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/, message: '密码必须包含大小写字母和数字' }
            )
            break

        case 'confirmPassword':
            rules.push(
                { required: true, message: '请确认密码' },
                {
                    validator: (_, value) => {
                        if (!value || formData.password === value) {
                            return Promise.resolve()
                        }
                        return Promise.reject(new Error('两次输入的密码不一致'))
                    }
                }
            )
            break

        case 'fullName':
            rules.push(
                { required: true, message: '请输入真实姓名' },
                { max: 100, message: '姓名不能超过 100 个字符' }
            )
            break

        case 'organization':
            rules.push(
                { max: 200, message: '机构名称不能超过 200 个字符' }
            )
            break

        case 'department':
            rules.push(
                { max: 100, message: '部门名称不能超过 100 个字符' }
            )
            break

        case 'phone':
            rules.push(
                { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码' }
            )
            break

        case 'applicationReason':
            rules.push(
                { required: true, message: '请输入申请理由' },
                { max: 1000, message: '申请理由不能超过 1000 个字符' }
            )
            break
    }

    return rules
}